package com.soft.mainsite.module.web.cms;

import com.google.common.collect.Maps;
import com.soft.mainsite.common.annotation.SysLog;
import com.soft.mainsite.common.constant.CmsConst;
import com.soft.mainsite.common.exception.CmsException;
import com.soft.mainsite.common.utils.*;
import com.soft.mainsite.module.city.entity.City;
import com.soft.mainsite.module.city.service.CityService;
import com.soft.mainsite.module.sensitiveword.service.SensitiveWordService;
import com.soft.mainsite.module.staticstrategy.staticservice.StaticHtmlService;
import com.soft.mainsite.module.web.cms.service.*;
import com.soft.mainsite.module.web.cms.vo.TCmsContentQueryParams;
import com.soft.mainsite.module.web.cms.vo.TCmsContentVo;
import com.soft.mainsite.module.web.cms.vo.TCmsSiteVo;
import com.soft.mainsite.module.web.system.vo.UserVo;
import com.soft.mainsite.mybatis.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Description:内容管理控制器
 *
 * @author Jin
 * @create 2017-04-17
 **/
@Slf4j
@Controller
@RequestMapping("/system/cms/content")
public class ContentController {

    public static final String TIME_SHOW = "1";
    public static final String SUPER_ADMIN = "superAdmin";
    public static final String OPERATION_ADMIN = "operationAdmin";
    @Autowired
    private ContentService contentService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ModelService modelService;

    @Autowired
    private ModelFiledService modelFiledService;

    @Autowired
    private SiteService siteService;

    @Autowired
    private SensitiveWordService sensitiveWordService;

    @Autowired
    private StaticHtmlService staticHtmlService;

    @Autowired
    private CityService cityService;

    @RequestMapping
    public String index() {
        return "cms/content";
    }

    @RequiresPermissions("content:admin")
    @RequestMapping("/page")
    public String page(@RequestParam(value = "pageCurrent", defaultValue = "1") Integer pageNumber,
                       @RequestParam(value = "pageSize", defaultValue = "30") Integer pageSize,
                       TCmsContentVo content,
                       Model model) {
        Subject currentUser = SecurityUtils.getSubject();
        TCmsCategory category = categoryService.findById(content.getCategoryId());
        if (!CmsUtil.isNullOrEmpty(content.getCategoryId()) && !StrUtil.isBlank(category.getPermissionKey()) && !currentUser.isPermitted(category.getPermissionKey())) {
            throw new CmsException("对不起,您没有当前栏目的管理权限！");
        }
        UserVo userVo = ((UserVo) ControllerUtil.getHttpSession().getAttribute(CmsConst.SITE_USER_SESSION_KEY));
        if (CmsUtil.isNullOrEmpty(userVo)) {
            throw new UnauthenticatedException();
        }
        content.setSiteId(userVo.getSiteId());
        content.setUserId(userVo.getUserId());
        model.addAttribute("model", contentService.page(pageNumber, pageSize, content));
        model.addAttribute("pojo", content);
        return "cms/content_list";
    }

    @RequiresPermissions("content:admin")
    @RequestMapping("/pageContent")
    public String pageContent(@RequestParam(value = "pageCurrent", defaultValue = "1") Integer pageNumber,
                              @RequestParam(value = "pageSize", defaultValue = "30") Integer pageSize,
                              TCmsContentVo content,
                              Model model) {
        Subject currentUser = SecurityUtils.getSubject();
        TCmsCategory category = categoryService.findById(content.getCategoryId());
        if (!CmsUtil.isNullOrEmpty(content.getCategoryId()) && !StrUtil.isBlank(category.getPermissionKey()) && !currentUser.isPermitted(category.getPermissionKey())) {
            throw new CmsException("对不起,您没有当前栏目的管理权限！");
        }
        UserVo userVo = ((UserVo) ControllerUtil.getHttpSession().getAttribute(CmsConst.SITE_USER_SESSION_KEY));
        if (CmsUtil.isNullOrEmpty(userVo)) {
            throw new UnauthenticatedException();
        }

        content.setSiteId(userVo.getSiteId());

        //只有审核员及超级管理员能够查看所有内容
        if (SecurityUtils.getSubject().hasRole(SUPER_ADMIN) || SecurityUtils.getSubject().hasRole(OPERATION_ADMIN)) {
            content.setSiteId(null);
        }


        content.setUserId(userVo.getUserId());
        content.setOrderField("");
        content.setOrderDirection("");
        model.addAttribute("model", contentService.pageContent(pageNumber, pageSize, content));
        model.addAttribute("pojo", content);
        return "cms/content_list";
    }

    @SysLog("内容添加")
    @RequiresPermissions("content:input")
    @RequestMapping("/input")
    public String input(@RequestParam(value = "categoryId", required = false) Long categoryId,
                        @RequestParam(value = "contentId", required = false) Long contentId,
                        @RequestParam(value = "isWindow", defaultValue = "NO") String isWindow,
                        Model model, HttpServletRequest request) {
        TCmsCategory category = categoryService.findById(categoryId);
        if (CmsUtil.isNullOrEmpty(category)) {
            throw new CmsException("当前栏目已被删除！");
        }
        Subject currentUser = SecurityUtils.getSubject();
        if (!StrUtil.isBlank(category.getPermissionKey()) && !currentUser.isPermitted(category.getPermissionKey())) {
            throw new CmsException("对不起,您没有当前栏目的管理权限！");
        }
        TCmsModel cmsModel = modelService.findById(category.getModelId());
        List<TCmsModelFiled> cmsModelFileds = modelFiledService.findModelFiledListByModelId(cmsModel.getModelId());
        if (contentId != null) {
            model.addAttribute("content", contentService.findContentByContentIdAndTableName(contentId, cmsModel.getTableName()));
        }
        UserVo userVo = ((UserVo) request.getSession().getAttribute(CmsConst.SITE_USER_SESSION_KEY));
        TCmsSiteVo voById = siteService.findVoById(userVo.getSiteId());
        TCmsSite tCmsSite = siteService.findById(voById.getSiteId());
        List<City> districtList = cityService.getCityDistrictByCityParentCode(voById.getCityCode());
        model.addAttribute("districtList", districtList);
        model.addAttribute("site", tCmsSite);
        model.addAttribute("siteType", voById.getSiteType());
        model.addAttribute("modelFiled", cmsModelFileds);
        model.addAttribute("category", category);
        model.addAttribute("isWindow", isWindow);
        return "cms/content_input";
    }


    @RequestMapping("/excel")
    public ModelAndView excel() {
        ExcelUtil.exports2007("123", contentService.page(1, 20, new TCmsContentVo()).getList());
        return null;
    }

    @RequiresPermissions("content:save")
    @RequestMapping("/save")
    @ResponseBody
    public String save(TCmsContentQueryParams contentQueryParams, HttpServletRequest request,
                       @RequestParam(value = "tag", required = false) String[] tags
    ) throws SQLException {
        UserVo userVo = ((UserVo) request.getSession().getAttribute(CmsConst.SITE_USER_SESSION_KEY));
        String contentId = request.getParameter("contentId");
        Integer siteId = userVo.getSiteId();
        if (contentId != null && !"".equals(contentId)) {
            Integer contentSiteId = contentService.findById(Long.parseLong(contentId)).getSiteId();
            if (siteId.equals(contentSiteId)) {
                contentQueryParams.setSiteId(siteId);
            } else {
                contentQueryParams.setSiteId(contentSiteId);
            }
        }


        TCmsCategory category = categoryService.findById(contentQueryParams.getCategoryId());
        TCmsModel cmsModel = modelService.findById(category.getModelId());
        List<TCmsModelFiled> cmsModelFileds = modelFiledService.findModelFiledListByModelId(category.getModelId());

        /*Jin：使用Map接收：遍历获取自定义模型字段*/
        Map<String, Object> modelFiledsMap = getFormParamFromCmsModelFileds(request, cmsModelFileds);
        // 发布内容中的敏感词
        String contentWord = sensitiveWordService.checkSensitiveWord(contentQueryParams.toString());
        // 栏目中的敏感词
        String categoryWord = sensitiveWordService.checkSensitiveWord(category.toString());
        // 模型字段中的敏感词
        String modelFiledWord = sensitiveWordService.checkSensitiveWord(modelFiledsMap.toString());

        contentQueryParams.setUserId(userVo.getUserId());
        contentQueryParams.setInputdate(new Date());

        contentQueryParams.setModelId(category.getModelId());

        TCmsContent tCmsContent = TCmsContentQueryParams.convertToEntity(contentQueryParams);

        String result;
        if (tCmsContent.getImageUrl() == null) {
            tCmsContent.setImageUrl("");
        } else {
            String imageUrl = tCmsContent.getImageUrl();
            if (imageUrl.lastIndexOf(CmsConst.PUNCTUATION_COMMA) != imageUrl.length() - 1) {
                tCmsContent.setImageUrl(tCmsContent.getImageUrl() + ",");
            }
        }
        if (tCmsContent.getContentId() != null) {
            result = contentService.update(tCmsContent, cmsModel.getTableName(), cmsModelFileds, modelFiledsMap, tags);
            return result;
        }
        result = contentService.save(tCmsContent, cmsModel.getTableName(), modelFiledsMap, tags);
        return result;
    }

    /**
     * 获取模型字段
     *
     * @param request
     * @param cmsModelFileds
     * @return
     */
    private Map<String, Object> getFormParamFromCmsModelFileds(HttpServletRequest request, List<TCmsModelFiled> cmsModelFileds) {
        Map<String, Object> formParam = Maps.newHashMap();
        for (TCmsModelFiled filed : cmsModelFileds) {
            if ("checkbox".equals(filed.getFiledClass()) || "image".equals(filed.getFiledClass())) {
                String[] filedValue = request.getParameterValues(filed.getFiledName());
                if (filedValue != null) {
                    formParam.put(filed.getFiledName(), filedValue);
                } else {
                    formParam.put(filed.getFiledName(), "");
                }
            } else {
                String filedValue = request.getParameter(filed.getFiledName());
                if (!StrUtil.isBlank(filedValue)) {
                    formParam.put(filed.getFiledName(), filedValue);
                }
            }
        }
        return formParam;
    }

    @SysLog("内容删除")
    @RequiresPermissions("content:delete")
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(@RequestParam(value = "ids", required = false) Long[] ids) {

        try {
            staticHtmlService.clearStaticHtml(ids);
        } catch (Exception e) {
            log.error("删除内容静态化失败", e);
        }
        return JsonUtil.toSuccess("操作成功", "content-tab", false);
    }


    @RequestMapping("/recovery")
    @ResponseBody
    public String recovery(@RequestParam(value = "ids", required = false) Long[] ids) {
        return contentService.recovery(ids);
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(true);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    /**
     * 修改发布状态
     *
     * @param ids
     * @return java.lang.String
     * @author 胡佳明
     * @date 2019/4/22 16:29
     */
    @RequiresPermissions("content:audit")
    @RequestMapping("/audit")
    @ResponseBody
    public String audit(@RequestParam(value = "ids", required = false) Long[] ids) {
        Integer integer = contentService.updateAudit(ids);
        if (integer > 0) {
            return JsonUtil.toSuccess("审核成功！", "content-tab", true);
        }
        return JsonUtil.toError("审核失败！");
    }

    /**
     * 审核不通过
     *
     * @param ids
     * @return 审核结果
     * @author 胡佳明
     * @date 2019/4/22 16:29
     */
    @RequiresPermissions("content:audit")
    @RequestMapping("/auditFail")
    @ResponseBody
    public String auditFail(@RequestParam(value = "ids", required = false) Long[] ids) {
        Integer integer = contentService.auditFail(ids);
        if (integer > 0) {
            return JsonUtil.toSuccess("操作成功！", "content-tab", true);
        }
        return JsonUtil.toError("操作失败！");
    }
}
